package com.utonw.carloan.function;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.support.v4.content.FileProvider;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.bigkoo.pickerview.TimePickerView;
import com.sensetime.sample.common.BankCardActivity;
import com.utonw.carloan.R;
import com.utonw.carloan.bean.other.ProvinceBean;
import com.utonw.carloan.global.Constants;
import com.utonw.carloan.global.ReleaseData;
import com.utonw.carloan.utils.JsonUtils;
import com.utonw.carloan.utils.UIUtils;
import com.wevey.selector.dialog.DialogInterface;
import com.wevey.selector.dialog.MDSelectionDialog;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

/**
 * Created by SEELE on 2017/3/27.
 */

/**
 * 全局方法类，包含显示PickerView及Dialog等
 */
public class GlobalLoanFunction {
    private String tx;
    private OptionsPickerView mPvOriWithClick;
    private OptionsPickerView mPvOriWithoutClick;
    private OptionsPickerView mPvLocal;
    private ArrayList<String> mTempData;
    private TextView toShow;
    private TimePickerView mPvTime;
    private MDSelectionDialog mMdSelectionDialogImage;
    private MDSelectionDialog mMdSelectionDialogUploadMethod;
    private ArrayList<String> mDatasImage;
    private ArrayList<String> mDatasUploadMethod;

    /**
     * 省市区List
     */
    private ArrayList<ProvinceBean> provinceBeanList = new ArrayList<>();
    private ArrayList<List<String>> cityList = new ArrayList<>();
    private ArrayList<List<List<String>>> districtList = new ArrayList<>();
    private String city;


    //设置临时数据
    public GlobalLoanFunction setTempData(ArrayList<String> tempDataParam, TextView toShow) {
        if (null != tempDataParam) {
            mTempData = new ArrayList<>();
            mTempData.addAll(tempDataParam);
            ReleaseData.tempList.add(mTempData);
        }
        this.toShow = toShow;
        return this;
    }

    //原版PickerView生成器,带点击监听（需要数据源）
    public void oriPickerView(final Context context, final OnClickPickerViewInterface onClickPickerView) {
        //条件选择器
        if (null != mPvOriWithClick) {
            mPvOriWithClick.setPicker(getTempData());
            UIUtils.hideSoftKeyboard(context);
            mPvOriWithClick.show();

        } else {
            mPvOriWithClick = new OptionsPickerView.Builder(context, new OptionsPickerView.OnOptionsSelectListener() {
                @Override
                public void onOptionsSelect(int options1, int option2, int options3, View v) {
                    //返回选中字段
                    tx = getTempData().get(options1);
                    getToShow().setTextColor(UIUtils.getColor(R.color.fontColor));
                    getToShow().setText(tx);
                    onClickPickerView.onClickPickerView();
                }
            })
                    .setSubmitColor(UIUtils.getColor(R.color.colorMyTheme))//确定按钮文字颜色
                    .setCancelColor(UIUtils.getColor(R.color.colorMyTheme))//取消按钮文字颜色
                    .build();
            mPvOriWithClick.setPicker(getTempData());
            UIUtils.hideSoftKeyboard(context);
            mPvOriWithClick.show();
        }


    }

    //原版PickerView生成器,不带点击监听（需要数据源）
    public void oriPickerView(final Context context) {
        //条件选择器
        if (null != mPvOriWithoutClick) {
            mPvOriWithoutClick.setPicker(getTempData());
            UIUtils.hideSoftKeyboard(context);
            mPvOriWithoutClick.show();

        } else {
            mPvOriWithoutClick = new OptionsPickerView.Builder(context, new OptionsPickerView.OnOptionsSelectListener() {
                @Override
                public void onOptionsSelect(int options1, int option2, int options3, View v) {
                    //返回选中字段
                    tx = getTempData().get(options1);
                    getToShow().setTextColor(UIUtils.getColor(R.color.fontColor));
                    getToShow().setText(tx);
                }
            })
                    .setSubmitColor(UIUtils.getColor(R.color.colorMyTheme))//确定按钮文字颜色
                    .setCancelColor(UIUtils.getColor(R.color.colorMyTheme))//取消按钮文字颜色
                    .build();
            mPvOriWithoutClick.setPicker(getTempData());
            UIUtils.hideSoftKeyboard(context);
            mPvOriWithoutClick.show();
        }


    }

    //时间选择器
    public void timePickerView(final Context context) {

        if (null != mPvTime) {
            mPvTime.setDate(Calendar.getInstance());//注：根据需求来决定是否使用该方法（一般是精确到秒的情况），此项可以在弹出选择器的时候重新设置当前时间，避免在初始化之后由于时间已经设定，导致选中时间与当前时间不匹配的问题。
            UIUtils.hideSoftKeyboard(context);
            mPvTime.show();

        } else {
            Calendar calendar = Calendar.getInstance();
            mPvTime = new TimePickerView.Builder(context, new TimePickerView.OnTimeSelectListener() {
                @Override
                public void onTimeSelect(Date date, View v) {//选中事件回调
                    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA);
                    getToShow().setTextColor(UIUtils.getColor(R.color.fontColor));
                    getToShow().setText(format.format(date));
                }
            })
                    .setType(TimePickerView.Type.YEAR_MONTH_DAY)//设置以年 月 日出现
                    .setRange(calendar.get(Calendar.YEAR) - 100, calendar.get(Calendar.YEAR))//default 1900-2100 years
                    .setSubmitColor(UIUtils.getColor(R.color.colorMyTheme))//确定按钮文字颜色
                    .setCancelColor(UIUtils.getColor(R.color.colorMyTheme))//取消按钮文字颜色
                    .build();


            mPvTime.setDate(calendar);
            //注：根据需求来决定是否使用该方法（一般是精确到秒的情况），此项可以在弹出选择器的时候重新设置当前时间，避免在初始化之后由于时间已经设定，导致选中时间与当前时间不匹配的问题。
            UIUtils.hideSoftKeyboard(context);
            mPvTime.show();
        }

    }

    //地区选择器
    public void localPickerView(final Context context) {
        //条件选择器
        if (null != mPvLocal) {
            UIUtils.hideSoftKeyboard(context);
            mPvLocal.show();

        } else {
            String province_data_json = JsonUtils.getJson(context, "province_data.json");
            parseJson(province_data_json);
            mPvLocal = new OptionsPickerView.Builder(context, new OptionsPickerView.OnOptionsSelectListener() {
                @Override
                public void onOptionsSelect(int options1, int option2, int options3, View v) {
                    //返回选中字段
                    getToShow().setTextColor(UIUtils.getColor(R.color.fontColor));
                    //返回的分别是三个级别的选中位置
                    city = provinceBeanList.get(options1).getPickerViewText();
                    //省 字段

                    String address;
                    //  如果是直辖市或者特别行政区只设置市和区/县
                    if ("北京市".equals(city) || "上海市".equals(city) || "天津市".equals(city) || "重庆市".equals(city) || "澳门".equals(city) || "香港".equals(city)) {
                        address = provinceBeanList.get(options1).getPickerViewText()
                                + " " + districtList.get(options1).get(option2).get(options3);

                    } else {
                        address = provinceBeanList.get(options1).getPickerViewText()
                                + " " + cityList.get(options1).get(option2)
                                + " " + districtList.get(options1).get(option2).get(options3);

                    }
                    getToShow().setText(address);


                }
            })
                    .setCyclic(false, false, false)//循环与否
                    .setSelectOptions(0, 0, 0)  //设置默认选中项
                    .setTitleText("城市选择")//标题
                    .setSubmitColor(UIUtils.getColor(R.color.colorMyTheme))//确定按钮文字颜色
                    .setCancelColor(UIUtils.getColor(R.color.colorMyTheme))//取消按钮文字颜色
                    .build();

            mPvLocal.setPicker(provinceBeanList, cityList, districtList);
            UIUtils.hideSoftKeyboard(context);
            mPvLocal.show();
        }


    }


    //弹出获取图片方式（相册，相机）
    public void showGetImageDialog(final Context context, final Fragment revFragment, final SendPathInterface sendPathInterface) {


        if (null != mMdSelectionDialogImage && null != mDatasImage) {

            mMdSelectionDialogImage.show();

        } else {
            mDatasImage = new ArrayList<>();
            mDatasImage.add("相册选取");
            mDatasImage.add("拍照");
            mDatasImage.add("取消");

            mMdSelectionDialogImage = new MDSelectionDialog.Builder(context)
                    .setCanceledOnTouchOutside(false)
                    .setItemTextColor(R.color.fontColor)
                    .setItemHeight(50)
                    .setItemWidth(0.8f)  //屏幕宽度*0.8
                    .setItemTextSize(14)
                    .setOnItemListener(new DialogInterface.OnItemClickListener<MDSelectionDialog>() {

                        @Override
                        public void onItemClick(MDSelectionDialog dialog, View button, int position) {
                            switch (position) {

                                case 0:
                                    //从相册选取
                                    dialog.dismiss();
                                    getImageFromAblum(context, revFragment);
                                    break;

                                case 1:
                                    //拍照上传
                                    dialog.dismiss();
                                    getImageFromCamera(context, revFragment, sendPathInterface);
                                    break;

                                case 2:
                                    dialog.dismiss();
                                    break;
                            }

                        }

                    })
                    .build()
                    .setDatas(mDatasImage);
            mMdSelectionDialogImage.show();

        }

    }


    //弹出扫描方式（横版，竖版）
    public void showUploadMethodDialog(final Context context, final Fragment revFragment, final int CardType) {

        if (null != mDatasUploadMethod) {

        } else {
            mDatasUploadMethod = new ArrayList<>();
            mDatasUploadMethod.add("扫描横版银行卡");
            mDatasUploadMethod.add("扫描竖版银行卡");
            mDatasUploadMethod.add("取消");
        }

        mMdSelectionDialogUploadMethod = new MDSelectionDialog.Builder(context)
                .setCanceledOnTouchOutside(false)
                .setItemTextColor(R.color.fontColor)
                .setItemHeight(50)
                .setItemWidth(0.8f)  //屏幕宽度*0.8
                .setItemTextSize(14)
                .setOnItemListener(new DialogInterface.OnItemClickListener<MDSelectionDialog>() {

                    @Override
                    public void onItemClick(MDSelectionDialog dialog, View button, int position) {
                        switch (position) {

                            case 0:
                                //扫描横版银行卡
                                dialog.dismiss();
                                Intent intent1 = new Intent(context, BankCardActivity.class);
                                intent1.putExtra(BankCardActivity.EXTRA_CARD_ORIENTATION, BankCardActivity.CARD_ORIENTATION_HORIZONTAL);
                                intent1.putExtra("whereToUpload", CardType);
                                revFragment.startActivityForResult(intent1, Constants.REQUEST_CODE_SCAN);

                                break;

                            case 1:
                                //扫描竖版银行卡
                                dialog.dismiss();
                                Intent intent2 = new Intent(context, BankCardActivity.class);
                                intent2.putExtra(BankCardActivity.EXTRA_CARD_ORIENTATION, BankCardActivity.CARD_ORIENTATION_VERTICAL);
                                intent2.putExtra("whereToUpload", CardType);
                                revFragment.startActivityForResult(intent2, Constants.REQUEST_CODE_SCAN);

                                break;

                            case 2:
                                dialog.dismiss();
                                break;
                        }

                    }

                })
                .build()
                .setDatas(mDatasUploadMethod);
        mMdSelectionDialogUploadMethod.show();


    }

    /**
     * 从相机获取图片
     */
    private void getImageFromCamera(Context context, Fragment fragment, SendPathInterface sendPathInterface) {
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        Date date = new Date(System.currentTimeMillis());
        String mFileName = format.format(date);
        //存储至DCIM文件夹
        File path = Environment
                .getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
        File outputImage = new File(path, mFileName + ".jpg");

        String imagePath = null;
        try {
            if (outputImage.exists()) {
                outputImage.delete();
            }
            if (outputImage.createNewFile()) {
                imagePath = path + "/" + mFileName + ".jpg";
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

        Uri mImageUri = null;
        if (Build.VERSION.SDK_INT < 23) {
            //将File对象转换为Uri并启动照相程序
            mImageUri = Uri.fromFile(outputImage);
            sendPathInterface.sendCamFilePath(imagePath, mImageUri);

        } else {
            //适配7.0
            mImageUri = FileProvider.getUriForFile(context,
                    context.getApplicationContext().getPackageName() + ".provider",
                    outputImage);
            sendPathInterface.sendCamFilePath(imagePath, mImageUri);
        }


        Intent intent = new Intent("android.media.action.IMAGE_CAPTURE"); //照相
        intent.putExtra(MediaStore.EXTRA_OUTPUT, mImageUri); //指定图片输出地址
        if (null != fragment) {
            fragment.startActivityForResult(intent, Constants.REQUEST_CAMERA); //启动照相
        } else {
            ((Activity) context).startActivityForResult(intent, Constants.REQUEST_CAMERA);
        }
    }

    /**
     * 从相册获取图片
     *
     * @param context
     * @param fragment
     */
    private void getImageFromAblum(Context context, Fragment fragment) {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("image/*");
        if (null != fragment) {
            fragment.startActivityForResult(intent, Constants.REQUEST_ALBUM);
        } else {
            ((Activity) context).startActivityForResult(intent, Constants.REQUEST_ALBUM);
        }
    }

    //回调照相路径接口
    public interface SendPathInterface {
        void sendCamFilePath(String path, Uri mImageUri);
    }

    //解析省市区数据
    private void parseJson(String str) {
        try {
            JSONArray jsonArray = new JSONArray(str);
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject provinceObject = jsonArray.optJSONObject(i);
                String provinceName = provinceObject.getString("name");
                provinceBeanList.add(new ProvinceBean(provinceName));
                JSONArray cityArray = provinceObject.optJSONArray("city");
                ArrayList<String> cities = new ArrayList<>();
                ArrayList<List<String>> districts = new ArrayList<>();
                for (int j = 0; j < cityArray.length(); j++) {
                    JSONObject cityObject = cityArray.optJSONObject(j);
                    String cityName = cityObject.optString("name");
                    cities.add(cityName);
                    ArrayList<String> district = new ArrayList<>();
                    JSONArray areaArray = cityObject.optJSONArray("area");
                    for (int k = 0; k < areaArray.length(); k++) {
                        String areaName = areaArray.getString(k);
                        district.add(areaName);
                    }
                    districts.add(district);
                }
                districtList.add(districts);
                cityList.add(cities);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    //设置EditText为：小数+后两位
    public static void setPricePoint(final EditText editText) {
        editText.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {
                if (s.toString().contains(".")) {
                    if (s.length() - 1 - s.toString().indexOf(".") > 2) {
                        s = s.toString().subSequence(0,
                                s.toString().indexOf(".") + 3);
                        editText.setText(s);
                        editText.setSelection(s.length());
                    }
                }
                if (s.toString().trim().substring(0).equals(".")) {
                    s = "0" + s;
                    editText.setText(s);
                    editText.setSelection(2);
                }

                if (s.toString().startsWith("0")
                        && s.toString().trim().length() > 1) {
                    if (!s.toString().substring(1, 2).equals(".")) {
                        editText.setText(s.subSequence(0, 1));
                        editText.setSelection(1);
                        return;
                    }
                }
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                // TODO Auto-generated method stub

            }

        });
        editText.setInputType(EditorInfo.TYPE_CLASS_NUMBER | EditorInfo.TYPE_NUMBER_FLAG_DECIMAL);
    }

    //设置EditText为：纯数字
    public static void setNumberPoint(final EditText editText) {
        editText.setInputType(EditorInfo.TYPE_CLASS_NUMBER);
    }

    //获取赋值的TextView
    public TextView getToShow() {
        return toShow;
    }

    //获取临时数据源
    private ArrayList<String> getTempData() {
        return mTempData;
    }

    //回调照相路径接口
    public interface OnClickPickerViewInterface {
        void onClickPickerView();
    }

}
